package com.education.welco.controller.app;

import com.education.common.core.BaseController;
import com.education.common.pojo.AjaxResult;
import com.education.common.utils.ApiReturnObject;
import com.education.websocket.data.HomeBuffer;
import com.education.websocket.data.HomeData;
import com.education.websocket.server.WebSocketServerWELCO;
import com.education.welco.feign.userFeign;
import com.education.welco.pojo.SCatalogMenu;
import com.education.welco.pojo.SCatalogWork;
import com.education.welco.pojo.StudentWork;
import com.education.welco.service.ISCatalogMenuService;
import com.education.welco.service.ISCatalogWorkService;
import com.education.welco.service.IStudentWorkService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 学生作业 信息操作处理
 *
 * @author d
 * @date 2022-06-27
 */
@RestController
@RequestMapping("/app/studentWork")
public class AppStudentWorkController extends BaseController {

    @Autowired
    private userFeign userFeign;
    @Autowired
    private ISCatalogWorkService catalogWorkService;
    @Autowired
    private IStudentWorkService studentWorkService;
    @Autowired
    private ISCatalogMenuService catalogMenuService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HomeBuffer homeBuffer;


    /**
     * 查所有二级目录下的作业列表  首先得到二级目录列表   根据二级目录id去查找（in）  关联答疑表
     *
     * @param lessonIdTop 课程0级id  找所有的二级目录
     * @param lessonIdTwo 课程2级id  二级目录
     * @param stuId       用户id     根据学生作业表的数据判断作业的当前状态 [作业当前状态   待提交(未查到)、批改中1、驳回2、已完成3]
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "查所有二级目录下的作业列表", httpMethod = "GET")
    public AjaxResult sAnsweringList(@RequestParam(value = "lessonIdTop", required = true) Integer lessonIdTop,
                                     @RequestParam(value = "lessonIdTwo", required = false) Integer lessonIdTwo,
                                     @RequestParam(value = "courseId", required = true) String courseId,
                                     @RequestParam(value = "stuId", required = true) Integer stuId) {

        //获取二级目录集合
        List<SCatalogMenu> TwoCataList = selectTwoList(lessonIdTop);
        //流转换对象
        List<Integer> twoIntList = TwoCataList.stream().map(a -> a.getId()).collect(Collectors.toList());
        //查找所有二级目录下的课堂作业资源
        SCatalogWork sCatalogWork = new SCatalogWork();
        sCatalogWork.setStuId(stuId);
        sCatalogWork.setIsStu("1");
        //sCatalogWork.setClassId(classId);//去掉中间表
        sCatalogWork.setTwoIDList(twoIntList);
        //1.获取学生已经提交的作业  批改中1、驳回2、已完成3
        List<SCatalogWork> sCatalogWorkList = catalogWorkService.selectSCatalogWorkStuList(sCatalogWork);

        /*//2.获取学生未提交的作业    获取总的作业id，已提交的作业id
        //获取总的作业id集合
        List<Integer> sCatalogWorksAll = catalogWorkService.selectSCatalogWorkStuListAll(sCatalogWork);
        //流转换对象
        //List<Integer> sCatalogWorksAllInt = sCatalogWorksAll.stream().map(a -> a.getId()).collect(Collectors.toList());
        //已提交的作业id
        List<Integer> sCatalogWorksSome = catalogWorkService.selectSCatalogWorkStuListSome(courseId, stuId);
        //找出未做作业的作业
        List<Integer> other = new ArrayList<>();
        for (Integer all : sCatalogWorksAll) {
            if (!sCatalogWorksSome.contains(all)) {
                other.add(all);
            }
        }
        //根据otherlist 查寻未提交作业
        if (other.size() > 0) {
            List<SCatalogWork> sCatalogWorksOther = catalogWorkService.selectSCatalogWorkStuListOther(other);
            sCatalogWorkList.addAll(sCatalogWorksOther);
        }*/

        //lessonIdTwo  进而确定是查全部列表还是某个二级目录下
        if (null != lessonIdTwo) {
            //map过滤
            List<SCatalogWork> collect = sCatalogWorkList.stream().filter(aaa -> String.valueOf(aaa.getCatalogId()).equals(String.valueOf(lessonIdTwo))).collect(Collectors.toList());
            PageInfo<SCatalogWork> objectPageInfo = new PageInfo<>(collect);
            return AjaxResult.success(objectPageInfo);
        }

        PageInfo<SCatalogWork> objectPageInfo = new PageInfo<>(sCatalogWorkList);
        return AjaxResult.success(objectPageInfo);
    }

    public List<SCatalogMenu> selectTwoList(Integer lessonId) {
        SCatalogMenu sCatalogMenu = new SCatalogMenu();
        //查询出第1级列表
        sCatalogMenu.setParentId(0);
        sCatalogMenu.setId(lessonId);
        SCatalogMenu list = catalogMenuService.selectSCatalogMenuList2(sCatalogMenu);
        //二级 以及 下面子列表
        return listSon2(list);
    }

    /**
     * 查询目录列表
     *
     * @param cList
     * @return
     */
    public List<SCatalogMenu> listSon2(SCatalogMenu cList) {
        //根据课程id查询出一级目录列表jrCatalogs
        List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //cList.setChildren(listSon(jrCatalogs));
            return listSon(jrCatalogs);
        }
        return null;
    }

    public List<SCatalogMenu> listSon(List<SCatalogMenu> cList) {
        List<SCatalogMenu> twoSCatalogMenu = new ArrayList<>();
        for (SCatalogMenu catalogMenu : cList) {
            //根据第一级的id查询出二级列表
            List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(catalogMenu.getId());
            //二级列表汇总
            twoSCatalogMenu.addAll(jrCatalogs);
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                //catalogMenu.setChildren(listSon(jrCatalogs));
                //catalogMenu.setChildren(jrCatalogs);
            }
        }
        return twoSCatalogMenu;
    }

    /**
     * 查询学生作业列表
     *
     */
    /*@GetMapping("/list")
    public ApiReturnObject list(StudentWork studentWork, Integer pageNum, Integer pageSize) {
        if(pageNum != null && pageSize !=null ){
            PageHelper.startPage(pageNum,pageSize);
        }
        List<StudentWork> list = studentWorkService.selectStudentWorkList(studentWork);
        PageInfo pageInfo = new PageInfo<>(list);
        return new ApiReturnObject("200","查询成功",pageInfo);
    }*/


    /**
     * 新增保存学生作业 workAdd
     *
     * @param courseId  课堂id
     * @param teaWorkId 老师布置的作业id
     * @param workText  学生回答内容
     * @param workImage 学生回答图片
     * @param userId    学生用户id
     * @return ApiReturnObject
     * 老师作业id*tea_work_id、作业回答内容*work_text、作业上传图片*work_image、学生id*user_id、作业状态1、创建人、创建时间
     */
    @PostMapping("/workAdd")
    //public ApiReturnObject addSave(@RequestBody StudentWork studentWork) {
    public ApiReturnObject addSave(Integer courseId, String teaWorkId, String workText, String workImage, String userId) {
        StudentWork studentWork = new StudentWork();
        studentWork.setTeaWorkId(teaWorkId);
        studentWork.setWorkText(workText);
        studentWork.setWorkImage(workImage);
        studentWork.setUserId(userId);
        studentWork.setCourseId(courseId);
        //根据userId搜索user  byUserId.get("name").toString(), byUserId.get("image").toString()
        Map<String, Object> byUserId = userFeign.findByUserId(Integer.valueOf(studentWork.getUserId()));

        //准备参数
        studentWork.setUserIco(byUserId.get("image").toString());
        studentWork.setUserName(byUserId.get("name").toString());
        studentWork.setWorkState("1");
        studentWork.setCreateBy(byUserId.get("name").toString());
        studentWork.setCreateTime(new Date());
        studentWork.setState("1");

        //首页待批改作业(老师id)
        studentWorkService.insertStudentWork(studentWork);
        //根据teaWorkId得到老师的userid
        String teaUserId = studentWorkService.selectTeaIdByTeaWorkId(teaWorkId);
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            homeData.setWorkWait(homeData.getWorkWait() + 1);
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, teaUserId);
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            homeData.setWorkWait(homeData.getWorkWait() + 1);
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }
        return new ApiReturnObject("200", "作业提交成功", "");
    }


    /**
     * 作业详情查询
     *
     * @param teaWorkId 老师布置的作业id
     * @param stuId     学生用户id
     * @return ApiReturnObject
     * 详情学生作业    老师布置的作业id，学生用户id
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer teaWorkId, Integer stuId) {
        StudentWork result = studentWorkService.selectStudentWorkById(teaWorkId, stuId);
        return new ApiReturnObject("200", "查询成功", result);
    }

    /**
     * 修改保存学生作业
     */
    @PostMapping("/update")
    public ApiReturnObject editSave(StudentWork studentWork) {
        studentWork.setWorkState("1");
        int i = studentWorkService.updateStudentWork(studentWork);
        //根据teaWorkId得到老师的userid
        String teaUserId = studentWorkService.selectTeaIdByTeaWorkId(studentWork.getTeaWorkId());
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            homeData.setWorkWait(homeData.getWorkWait() + 1);
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, teaUserId);
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            homeData.setWorkWait(homeData.getWorkWait() + 1);
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }
        return new ApiReturnObject("200", "修改成功", "");
    }

    /**
     * 删除学生作业
     */
    @PostMapping("/del")
    public ApiReturnObject remove(String ids) {
        studentWorkService.deleteStudentWorkByIds(ids);
        return new ApiReturnObject("200", "删除成功", "");
    }
}